package com.itcast.demo_one.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.itcast.demo_one.R
import com.itcast.demo_one.model.CityData

class MyAdapter( private val items: List<CityData>) : RecyclerView.Adapter<MyAdapter.ViewHolder>() {

    /**
     * ViewHolder类，用于缓存视图项中的控件
     * @param view 单项视图布局
     */
    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        // 要缓存的控件
        val cityIcon: ImageView = view.findViewById(R.id.cityIcon)
        val cityText: TextView = view.findViewById(R.id.cityText)
        val cityIntro: TextView = view.findViewById(R.id.cityIntro)
    }

    /**
     * 创建或加载ViewHolder对象，并返回
     * @param parent 父布局
     * @param viewType 视图类型
     * @return ViewHolder对象
     */
    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): ViewHolder {
        // 加载本地的xml
        // 加载的布局会正确测量
        val inflater = LayoutInflater.from(parent.context).inflate(R.layout.item_city_plus, parent, false)
        return ViewHolder(inflater)
    }


    /**
     * 绑定数据到ViewHolder对象中
     * @param holder ViewHolder对象
     * @param position 当前项的位置
     */
    override fun onBindViewHolder(
        holder: ViewHolder,
        position: Int
    ) {
        val item = items[position]
        holder.cityIcon.setImageResource(item.icon)
        holder.cityText.text = item.text
        holder.cityIntro.text = item.intro
    }

    override fun getItemCount(): Int {
        return items.size
    }
}